<script setup lang="tsx">
import { reactive, ref, unref } from 'vue'
import { ContentWrap } from '@/components/ContentWrap'
import { Table } from '@/components/Table'
import { BaseButton } from '@/components/Button'
import { ElMessageBox, ElSwitch, ElMessage } from 'element-plus'
import { useTable } from '@/hooks/web/useTable'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { isEmptyVal } from '@/utils/is'
import {
  getListApi,
  createApi,
  modifyApi,
  delApi,
  updateStatusApi,
  type Row
} from '@/api/product/classification'
import { useRouter } from 'vue-router'
defineOptions({
  name: 'ProjectClassification'
})
const switchLoading = ref(false)
const changeStatus = async (row) => {
  const val = {
    '1': 2,
    '2': 1
  }
  switchLoading.value = true
  try {
    const res = await updateStatusApi({ status: val[row.status], id: row.id })
    if (res) ElMessage.success(res.msg)
    return !!res
  } finally {
    switchLoading.value = false
  }
}
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'selection',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true },
    table: { type: 'selection' }
  },
  {
    field: 'name',
    label: '分类名称',
    form: { hidden: true },
    detail: { hidden: true },
    table: {
      align: 'left',
      headerAlign: 'left'
    }
  },
  {
    field: 'status',
    label: '状态',
    search: {
      component: 'Select',
      componentProps: {
        options: [
          {
            label: '正常',
            value: 1
          },
          {
            label: '禁用',
            value: 2
          }
        ]
      }
    },
    form: { hidden: true },
    detail: { hidden: true },
    table: {
      width: '200px',
      slots: {
        default: ({ row }) => {
          return (
            <ElSwitch
              v-model={row.status}
              active-value={1}
              inactive-value={2}
              loading={switchLoading.value}
              beforeChange={() => changeStatus(row)}
            />
          )
        }
      }
    }
  },
  {
    field: 'action',
    width: 'auto',
    label: '操作',
    search: { hidden: true },
    form: { hidden: true },
    detail: { hidden: true },
    table: {
      slots: {
        default: ({ row }) => {
          return (
            <>
              <BaseButton type="primary" onClick={() => modifyClassification(row)}>
                编辑
              </BaseButton>
              <BaseButton type="primary" onClick={() => delData(row)}>
                删除
              </BaseButton>
            </>
          )
        }
      }
    }
  }
])

const { allSchemas } = useCrudSchemas(crudSchemas)

const ids = ref<string[]>([])

const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const res = await getListApi()
    return {
      list: res.data
    }
  },
  fetchDelApi: async () => {
    const res = await delApi({ id: unref(ids).join(',') })
    return !!res
  }
})
const { loading, dataList } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const createClassification = async () => {
  try {
    const { value } = await ElMessageBox.prompt('', `新增分类`, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputPlaceholder: `请输入分类名称`,
      inputValidator: (val) => !isEmptyVal(val),
      inputErrorMessage: `请输入分类名称！`
    })
    const res = await createApi({ name: value })
    if (res) {
      ElMessage.success(res.msg)
      getList()
    }
  } catch (error: any) {
    if (error !== 'cancel') ElMessage.error(error.msg)
  }
}

const modifyClassification = async (row: Row) => {
  try {
    const { value } = await ElMessageBox.prompt('', `编辑`, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValue: row.name,
      inputValidator: (val) => !isEmptyVal(val),
      inputErrorMessage: '请输入分类名称！'
    })
    const res = await modifyApi({ name: value, id: row.id })
    if (res) {
      ElMessage.success(res.msg)
      getList()
    }
  } catch (error: any) {
    if (error !== 'cancel') ElMessage.error(error.msg)
  }
}

const delLoading = ref(false)

const delData = async (row: Row | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row ? [row.id] : elTableExpose?.getSelectionRows().map((v: Row) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}
const router = useRouter()

const gotoDetail = () => {
  router.push('list')
}
</script>
<template>
  <ContentWrap title="分类管理">
    <div class="mb-10px">
      <BaseButton type="primary" @click="createClassification">新增</BaseButton>
      <!-- <BaseButton :loading="delLoading" type="danger" @click="delData(null)">删除</BaseButton> -->
      <BaseButton type="success" @click="gotoDetail">返回商品列表</BaseButton>
    </div>

    <Table
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      @register="tableRegister"
    />
  </ContentWrap>
</template>
